package ru.mipt.sport.gui.registry;

import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.util.List;
import javax.persistence.EntityManager;
import javax.swing.*;
import javax.swing.event.TableModelEvent;
import ru.mipt.sport.gui.model.SportLevelsTableModel;
import ru.mipt.sport.model.entity.SportSpecializationEntity;
import ru.mipt.sport.model.interfaces.SportLevel;
import ru.mipt.sport.model.interfaces.SportSpecialization;
import ru.mipt.sport.utils.DBUtils;

/**
 *
 * @author Danon
 */
public class AddSportDialog extends javax.swing.JDialog {

    private final DBUtils db;
    /**
     * A return status code - returned if Cancel button has been pressed
     */
    public static final int RET_CANCEL = 0;
    /**
     * A return status code - returned if OK button has been pressed
     */
    public static final int RET_OK = 1;

    /**
     * Creates new form AddSportDialog
     */
    public AddSportDialog(java.awt.Frame parent, boolean modal, SportSpecialization sport) {
        super(parent, modal);
        initComponents();
        
        db = DBUtils.getInstance();
        refreshParentComboBox();
        
        if (sport == null) {
            sport = new SportSpecializationEntity();
            setTitle("New Sport specialization...");
            addLevelBtn.setEnabled(false);
        } else {
            setTitle("Sport Specialization");
        }
        this.sport = sport;

        jTable1.setModel(new SportLevelsTableModel(sport));
        
        fillForm();

        // Close the dialog when Esc is pressed
        String cancelName = "cancel";
        InputMap inputMap = getRootPane().getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
        inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), cancelName);
        ActionMap actionMap = getRootPane().getActionMap();
        actionMap.put(cancelName, new AbstractAction() {

            @Override
            public void actionPerformed(ActionEvent e) {
                doClose(RET_CANCEL);
            }
        });
    }

    public final void refreshParentComboBox() {
        synchronized (db) {
            DefaultComboBoxModel<SportSpecialization> model = (DefaultComboBoxModel<SportSpecialization>) parentSportComboBox.getModel();
            Object o = model.getSelectedItem();
            model.removeAllElements();
            EntityManager em = db.getEntityManager();
            List<SportSpecialization> elements = em.createQuery("select s from SportSpecializationEntity s order by s.name", SportSpecialization.class).getResultList();
            if (elements != null) {
                for (SportSpecialization s : elements) {
                    model.addElement(s);
                }
            }
            model.addElement(null);
            model.setSelectedItem(o);
        }
    }

    private void fillForm() {
        sportNameTF.setText(sport.getName());
        descriptionTF.setText(sport.getDescription());
        parentSportComboBox.setSelectedItem(sport.getParent());
        sportTypeComboBox.setSelectedItem(sport.getType()==null ? "DEFAULT" : sport.getType());
    }

    private void processInput() {
        sport.setName(sportNameTF.getText());
        sport.setDescription(descriptionTF.getText());
        sport.setType(sportTypeComboBox.getSelectedItem().toString());
        sport.setParent((SportSpecializationEntity) parentSportComboBox.getSelectedItem());
    }

    /**
     * @return the return status of this dialog - one of RET_OK or RET_CANCEL
     */
    public int getReturnStatus() {
        return returnStatus;
    }
    
    public SportSpecialization getSport() {
        return sport;
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        okButton = new javax.swing.JButton();
        cancelButton = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        parentSportComboBox = new javax.swing.JComboBox();
        jLabel2 = new javax.swing.JLabel();
        sportNameTF = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        descriptionTF = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        sportTypeComboBox = new javax.swing.JComboBox();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jLabel5 = new javax.swing.JLabel();
        addLevelBtn = new javax.swing.JButton();
        removeLevelBtn = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Sport...");
        setResizable(false);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                closeDialog(evt);
            }
            public void windowClosed(java.awt.event.WindowEvent evt) {
                formWindowClosed(evt);
            }
        });

        okButton.setText("OK");
        okButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                okButtonActionPerformed(evt);
            }
        });

        cancelButton.setText("Cancel");
        cancelButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelButtonActionPerformed(evt);
            }
        });

        jLabel1.setText("Parent Sport:");

        parentSportComboBox.setModel(new DefaultComboBoxModel<SportSpecialization>());

        jLabel2.setText("Sport Name:");

        jLabel3.setText("Description:");

        jLabel4.setText("Sport Type:");

        sportTypeComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "SINGLE_RUN", "RELAY", "ATTEMPTS", "DEFAULT" }));
        sportTypeComboBox.setToolTipText("<html>\n<b>DEFAULT</b> - По умолчанию<br/>\n<b>SINGLE_RUN</b> - Одиночный забег<br/>\n<b>RELAY</b> - Эстафета<br/>\n<b>ATTEMPTS</b> - Попытки\n</html>");

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane1.setViewportView(jTable1);

        jLabel5.setText("Levels:");

        addLevelBtn.setText("Add level...");
        addLevelBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addLevelBtnActionPerformed(evt);
            }
        });

        removeLevelBtn.setText("Remove");
        removeLevelBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                removeLevelBtnActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1)
                            .addComponent(jLabel2)
                            .addComponent(jLabel3)
                            .addComponent(jLabel4))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(parentSportComboBox, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(sportNameTF)
                            .addComponent(descriptionTF)
                            .addComponent(sportTypeComboBox, 0, 275, Short.MAX_VALUE)))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(okButton, javax.swing.GroupLayout.PREFERRED_SIZE, 67, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(cancelButton))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel5)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(removeLevelBtn)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(addLevelBtn)))
                .addContainerGap())
        );

        layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {cancelButton, okButton});

        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(parentSportComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(sportNameTF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(descriptionTF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(sportTypeComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel4))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(addLevelBtn)
                    .addComponent(removeLevelBtn))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 166, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(cancelButton)
                    .addComponent(okButton))
                .addContainerGap())
        );

        getRootPane().setDefaultButton(okButton);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void okButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_okButtonActionPerformed
        processInput();
        doClose(RET_OK);
    }//GEN-LAST:event_okButtonActionPerformed

    private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
        doClose(RET_CANCEL);
    }//GEN-LAST:event_cancelButtonActionPerformed

    /**
     * Closes the dialog
     */
    private void closeDialog(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_closeDialog
        doClose(RET_CANCEL);
    }//GEN-LAST:event_closeDialog

    private void removeLevelBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_removeLevelBtnActionPerformed
        int a[] = jTable1.getSelectedRows();
        if(a==null || a.length == 0)
            return;
        SportLevelsTableModel model = (SportLevelsTableModel)jTable1.getModel();
        model.removeRows(a);
        jTable1.tableChanged(new TableModelEvent(model));
    }//GEN-LAST:event_removeLevelBtnActionPerformed

    private void addLevelBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addLevelBtnActionPerformed
        AddSportLevelDialog dlg = new AddSportLevelDialog(null, true);
        dlg.setVisible(true);
        if(dlg.getReturnStatus()==AddSportLevelDialog.RET_OK && sport.getId()!=null) {
            synchronized(db) {
                try {
                    EntityManager em = db.getEntityManager(true);
                    SportLevel level = dlg.getLevel();
                    level.setSport((SportSpecializationEntity)sport);
                    em.persist(level);
                    db.commit();
                } catch (Exception ex) {
                    db.rollback();
                }
            }
            SportLevelsTableModel model = (SportLevelsTableModel)jTable1.getModel();
            model.refresh();
            jTable1.tableChanged(new TableModelEvent(model));
        }
    }//GEN-LAST:event_addLevelBtnActionPerformed

    private void formWindowClosed(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosed
        db.close();
    }//GEN-LAST:event_formWindowClosed

    private void doClose(int retStatus) {
        returnStatus = retStatus;
        setVisible(false);
        dispose();
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(AddSportDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(AddSportDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(AddSportDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(AddSportDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the dialog
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                AddSportDialog dialog = new AddSportDialog(new javax.swing.JFrame(), true, null);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {

                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton addLevelBtn;
    private javax.swing.JButton cancelButton;
    private javax.swing.JTextField descriptionTF;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JButton okButton;
    private javax.swing.JComboBox parentSportComboBox;
    private javax.swing.JButton removeLevelBtn;
    private javax.swing.JTextField sportNameTF;
    private javax.swing.JComboBox sportTypeComboBox;
    // End of variables declaration//GEN-END:variables
    private int returnStatus = RET_CANCEL;
    private SportSpecialization sport;
}
